<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui, viewport-fit=cover">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>请假系统-申请请假</title>
  <link rel="stylesheet" href="vendor/weui/1.1.3/weui.min.css">
  <link rel="stylesheet" href="vendor/jquery-weui-1.2.1/jquery-weui.min.css">
  <link rel="stylesheet" href="assets/css/weui-my.css">
  
  <style>
    .banner-grid {
      padding: 60px 45px 15px 45px;
      height: 90px;
    }
    .banner-grid-row,
    .banner-grid-row:before,
    .banner-grid-row:after {
      clear: both;
    }
    .banner-grid-half-row {
      float: left;
      width: 50%;
      text-align: center;
    }
    .big-font {
      font-size: 28px;
      font-weight: 400;
    }
    .tag {
      color: #999;
    }
    .calendar {
      /* display: block; */
      width: 22px;
      height: 22px;
      background: url(assets/images/icon_tabbar.png);
      background-size: 100%;
      
      position: relative;
      display: inline-block;
      /* background: #D0EEFF;
      border: 1px solid #99D3F5;
      border-radius: 4px; */
      /* padding: 4px 12px; */
      overflow: hidden;
      /* color: #1E88C7;
      text-decoration: none;
      text-indent: 0;
      line-height: 20px; */
    }
    .calendar input {
      position: absolute;
      font-size: 100px;
      right: 0;
      top: 0;
      opacity: 0;
      filter: alpha(opacity=0);
    }
    
    /* 自定义日历样式 */
    .calendar-custom {
      /* background-color: rgba(255, 255, 200, 0.9); */
      height: 425px;
    }
    .calendar-custom .picker-modal-inner {
      /* background-color: rgba(255, 200, 200, 0.7); */
      height: 381px;
    }
    .calendar-custom .picker-calendar-months {
      /* background-color: rgba(255, 200, 255, 0.5); */
      height: 361px;
    }
    .calendar-custom .picker-calendar-row {
      height: 60px;
    }
    .calendar-custom .picker-calendar-day {
      border-bottom: 1px solid #eee;
      border-left: 1px solid #eee;
      box-sizing: border-box;
      flex-direction: column;
    }
    .calendar-custom .picker-calendar-day div {
      /* top: -10px; */
      height: 38px;
    }
    .calendar-custom .picker-calendar-day div:first-child {
    	/* top: -10px; */
    	height: 24px;
    }
    
    .mini-font {
      font-size: 12px;
      /* position: relative;; */
      /* top: 0px; */
      /* left: 10px; */
    }
  </style>
  
</head>
<body>
  <div class="weui-toptips weui-toptips_warn js_tooltips">错误提示</div>

  <div class="container" id="container">
    <div class="page searchbar js_show">
      <div class="banner-grid">
        <div class="banner-grid-row">
          <div class="banner-grid-half-row">
            <span class="big-font">7.5</span> 小时
          </div>
          <div class="banner-grid-half-row">
            <span class="big-font">2</span> 天
          </div>
        </div>
        <div class="banner-grid-row">
        	<div class="banner-grid-half-row">
        		<span class="tag">存休</span>
        	</div>
        	<div class="banner-grid-half-row">
        		<span class="tag">年假</span>
        	</div>
        </div>
      </div>
      
      <form id="leaveForm">
        <!-- 申请类型 -->
        <div class="weui-cells__title">
          <p>申请类型</p>
        </div>
        <div class="weui-cells weui-cells_form">
          <a class="weui-cell weui-cell_access invalid-event-handler" href="javascript: void(0);" onclick="document.activeElement.blur();">
            <div class="weui-cell__hd"><label class="weui-label">请假类别</label></div>
            <div class="weui-cell__bd">
              <input type="text" class="weui-input fake-leaveType" placeholder="请点击选择类别" readonly />
              <input type="hidden" class="weui-input" name="leaveType" id="leaveType" required tips="请选择请假类别" />
            </div>
            <div class="weui-cell__ft"> <i class="weui-icon-warn"></i> </div>
          </a>
          <a class="weui-cell weui-cell_access invalid-event-handler" href="javascript: void(0);" onclick="document.activeElement.blur(); selectAppliUuid();">
            <div class="weui-cell__hd"><label class="weui-label">申请类别</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" class="weui-input" name="appliUuid" id="appliUuid" required tips="请选择申请类别" />
            </div>
            <div class="weui-cell__ft">
              <i class="weui-icon-warn"></i>
            </div>
          </a>
        </div>
        
        <!-- 时间范围 -->
        <div class="weui-cells__title">
          <p>
            <span>时间范围</span>
            <i class="calendar pull-right" onclick="document.activeElement.blur();">
              <input type="text" class="fake-calendar">
            </i>
          </p>
        </div>
        
        <div class="weui-cells weui-cells_form">
          <a class="weui-cell weui-cell_access invalid-event-handler" href="javascript: void(0);" onclick="document.activeElement.blur();">
            <div class="weui-cell__hd"><label class="weui-label">开始时间</label></div>
            <div class="weui-cell__bd">
              <input type="text" class="weui-input" name="startTime" id="startTime" placeholder="请点击选择开始时间" required tips="请选择开始时间" />
            </div>
            <div class="weui-cell__ft">
              <i class="weui-icon-warn"></i>
            </div>
          </a>
          <a class="weui-cell weui-cell_access invalid-event-handler" href="javascript: void(0);" onclick="document.activeElement.blur();">
            <div class="weui-cell__hd"><label class="weui-label">结束时间</label></div>
            <div class="weui-cell__bd">
              <input type="text" class="weui-input" name="endTime" id="endTime" placeholder="请点击选择结束时间" required tips="请选择结束时间" />
            </div>
            <div class="weui-cell__ft">
              <i class="weui-icon-warn"></i>
            </div>
          </a>
        </div>
        
        <!-- 假单详情 -->
        <div class="weui-cells__title">
          <p>请假详情</p>
        </div>
        <div class="weui-cells weui-cells_form">
          <div class="weui-cell invalid-event-handler">
            <div class="weui-cell__bd">
              <textarea class="weui-textarea" name="reason" id="reason" pattern="^.{1,200}$" count-limit-max="200" placeholder="请输入文本" rows="3" required tips="请输入请假详情,最大200个字符长度"></textarea>
              <div class="weui-textarea-counter">
            <!-- <div class="weui-cell__ft"> -->
            <!-- </div> -->
                <span class="now-count"></span>/<span class="count-limit"></span>
                <i class="weui-icon-warn"></i>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 提交按钮 -->
        <div class="weui-cells no-line">
          <div class="weui-cell">
            <div class="weui-cell__bd">
              <a href="javascript: void(0);" class="weui-btn weui-btn_primary" onclick="document.activeElement.blur(); validate();">预览并提交请假</a>
            </div>
          </div>
        </div>
      </form>
      
    </div>
  </div>

  <!-- 预览 -->
  <div id="preview" class="weui-popup__container popup-bottom">
    <div class="weui-popup__overlay"></div>
    <div class="weui-popup__modal">
      
      <div class="weui-form-preview">
        <div class="weui-form-preview__hd">
            <em class="weui-form-preview__value" style="text-align: center;">
              <span prefor="leaveType">外出</span> - <span prefor="appliUuid">上班不能按时打卡</span>
            </em>
        </div>
        <div class="weui-form-preview__hd">
            <label class="weui-form-preview__label">请假小时数</label>
            <em class="weui-form-preview__value" prefor="hours">loading...</em>
        </div>
        <div class="weui-form-preview__bd">
            <div class="weui-form-preview__item">
                <label class="weui-form-preview__label">开始时间</label>
                <span class="weui-form-preview__value" prefor="startTime">2018-12-12 09:00</span>
            </div>
            <div class="weui-form-preview__item">
                <label class="weui-form-preview__label">结束时间</label>
                <span class="weui-form-preview__value" prefor="endTime">2018-12-12 18:00</span>
            </div>
            <div class="weui-form-preview__item">
                <label class="weui-form-preview__label">请假理由</label>
                <span class="weui-form-preview__value" prefor="reason">很长很长的名字很长很长的名字很长很长的名字很长很长的名字很长很长的名字</span>
            </div>
        </div>
        <div class="weui-form-preview__ft">
            <button type="button" class="weui-form-preview__btn weui-form-preview__btn_primary" href="javascript:" onclick="submit();">提交申请</button>
            <a class="weui-form-preview__btn weui-form-preview__btn_default" href="javascript:" onclick="$.closePopup();">取消</a>
        </div>
      </div>
    </div>
  </div>

  <script src="vendor/weuijs/1.1.4/weui.js"></script>
  <script src="vendor/jquery/jquery-1.11.0.min.js"></script>
  <script src="vendor/jquery.serializejson/jquery.serializejson.min.js"></script>
  <script src="vendor/jquery-weui-1.2.1/jquery-weui.js"></script>
  <script src="assets/js/common.js"></script>
  
  <script>
    var $leaveType = $('input[name=leaveType]');
    var $appliUuid = $('input[name=appliUuid]');
    
    // 请假类别和申请类别的层级数据
    $.ajax({
      method: 'get',
      url: 'data/data_leaveType_appliUuid.json',
      success: function (data) {
        initLeaveTypeAppliUuid(data.data);
      }
    });
    
    // 初始化联动的申请类别和请假类别
    var leaveType_valueMap = {};           // 请假类别_显示值=>实际值
    var leaveType_displayValues = [];      // 请假类别_显示值列表
    var appliUuid_valueMap = {};           // 申请类别_显示值=>实际值
    var appliUuid_displayValuesMap = {};   // 申请类别_请假类别实际值=>申请类显示值待选项列表
    function initLeaveTypeAppliUuid(leaveCascade) {
      // 初始化请假类别、申请类别的数据
      $.each(leaveCascade, function() {
        var ltItem = this;
        leaveType_valueMap[ltItem.label] = ltItem.value;
        
        appliUuid_displayValuesMap[ltItem.value] = [];
        $.each(ltItem.children, function() {
          var auItem = this;
          appliUuid_valueMap[auItem.label] = auItem.value;
          appliUuid_displayValuesMap[ltItem.value].push(auItem.label);
        })
        leaveType_displayValues.push(ltItem.label);
      })
      
      // 初始化请假类别、申请类别的数据
      /* leaveType_displayValues = leaveCascade.map((ltItem) => {
        leaveType_valueMap[ltItem.label] = ltItem.value;
        appliUuid_displayValuesMap[ltItem.value] = ltItem.children.map((auItem) => {
          appliUuid_valueMap[auItem.label] = auItem.value;
          return auItem.label
        });
        return ltItem.label
      }); */
      console.log('leaveType =>', leaveType_displayValues, leaveType_valueMap);
      console.log('appliUuid =>', appliUuid_displayValuesMap, appliUuid_valueMap);
      
      // 请假类别、申请类别 初始化
      $('.fake-leaveType').picker({
        title: "请选择“请假类别”",
        cols: [{
          textAlign: 'center',
          values: leaveType_displayValues
        }],
        onChange: function (pickerInstance, values) {
          // 每次显示值更新,同步修改实际值
          $leaveType.val(leaveType_valueMap[values[0]]);
          
          // 每次请假类别改变选项,都要销毁原申请类别对象,重新初始化,待选项值由请假类别实际值决定
          $('.fake-appliUuid').remove();
          $appliUuid.before('<input type="text" class="weui-input fake-appliUuid" placeholder="请点击选择类别" readonly />');
          $('.fake-appliUuid').picker({
            title: "请选择“申请类别”",
            cols: [{
              textAlign: 'center',
              values: appliUuid_displayValuesMap[$leaveType.val()]
            }],
            onChange: function (pickerInstance, values) {
              $appliUuid.val(appliUuid_valueMap[values[0]]);
            }
          });
        }
      });
    }
    
    // 校验申请类别
    function selectAppliUuid() {
      if (!$leaveType.val()) {
        /* $.notification({
          title: "提示",
          text: "请先选择“请假类别”!"
        }); */
        weui.topTips('请先选择“请假类别”!', {
        	duration: 5000,
        	callback: function callback() {
        		console.log('on shown callback');
        	}
        });
      }
    }
    
    var isRun = false;
    // 初始化日历
    $('.fake-calendar:eq(0)').calendar({
      cssClass: 'calendar-custom',
      onOpen: function() {
        if (!window.isRun) {
          window.isRun = true;
          setTimeout(function() {
            var arr = $('.picker-calendar-day');
            $.each(arr, function(idx) {
              var $c = $('<div></div>');
              $c.append($(arr[idx]).find('span'));
              $(arr[idx]).append($c);
              $(arr[idx]).append($('<div class="mini-font">09:01<br>19:20</div>'));
            });
            window.isRun = false;
          }, 16);
        }
        var reOpen = false;
        // 如果picker没有初始化过,用open方法调用初始化(居然在第一次open的时候初始化，贱贱的……)
        if (!$('input[name=startTime]').data('picker').initialized) {
          $('input[name=startTime]').picker('open');
          reOpen = true;
        }
        if (!$('input[name=endTime]').data('picker').initialized) {
          $('input[name=endTime]').picker('open');
          reOpen = true;
        }
        if (reOpen) {
          $('.fake-calendar:eq(0)').calendar('open');
        }
        // console.log('onOpen');
      },
      onClose: function() {
        // console.log('onClose');
      },
      onChange: function (p, displayValues, values) {
        // 使用setTimeout0改变代码运行顺序,避免先运行change方法再运行open方法带来的麻烦
        setTimeout(function() {
          // console.log('onChange', p, displayValues, values);
          var ts = new Date(values[0]);
          $('input[name=startTime]').picker('setValue', [ts.getFullYear() + "", ts.getMonth() + 1 + "", ts.getDate() + "", "09", "00"]);
          $('input[name=endTime]').picker('setValue', [ts.getFullYear() + "", ts.getMonth() + 1 + "", ts.getDate() + "", "18", "00"]);
        }, 0);
      }
    });
    
    // 初始化所有多行文本的文本计数器
    $('.weui-textarea').each(function() {
      var $t = $(this);
      var $c = $t.parent().find('.now-count');
      var $cl = $t.parent().find('.count-limit');
      var countLimit = $t.attr('count-limit-max');
      var count = $t.val().length;
      $c.html(count);
      $cl.html(countLimit);
      
      $t.on('input', function() {
        count = $t.val().length;
        $c.html(count);
        
        if (count > countLimit) {
          $c.css('color', 'red');
        } else {
          $c.css('color', 'inherit');
        }
      });
    });
    
    
    var yearsAllow = [];
    var now = new Date();
    var nowYear = now.getFullYear();
    for (var i = -1; i <= 1; i++) {
      yearsAllow.push(nowYear + i);
    }
    $('input[name=startTime]').on('change', function() {
      console.log('chagne>>>', $(this).val());
    });
    
    // 开始时间-初始化
    $('input[name=startTime]').datetimePicker({
      years: yearsAllow,
      title: "请选择“开始时间”",
      onChange: function (pickerInstance, values) {
        console.log('change', pickerInstance, values);
      }
    });
    
    // 结束时间-初始化
    $('input[name=endTime]').datetimePicker({
      years: yearsAllow,
      title: "请选择“结束时间”",
      onChange: function (pickerInstance, values) {
        console.log('change', pickerInstance, values);
      }
    });
    
    // 校验方法
    function validate() {
      // 校验
      weui.form.validate('#leaveForm', function (error) {
        console.log(error, !!error);
        // 有错
        if (!!error) {
          weui.topTips($(error.ele).attr('tips'), {
            duration: 5000,
            callback: function callback() {
              console.log('on shown callback');
            }
          });
          
          $(error.ele).closest('.invalid-event-handler').one('click', function() {
            $(this).removeClass('weui-cell_warn');
          });
        }
        // 无错
        else {
          popup_preview();
        }
      });
    }
    
    // 弹出预览层
    function popup_preview() {
      var $form = $(event.target).closest('form');
      var dataArr = $form.serializeArray();
      $.each(dataArr, function(idx) {
      	var name = dataArr[idx].name;
      	var val = dataArr[idx].value;
      	// 针对leaveType, appliUuid的特殊处理
      	if (['leaveType', 'appliUuid'].indexOf(name) != -1) {
      		$('[prefor=' + name + ']').html($('.fake-' + name).val());
      	}
      	// 其他
      	else {
      		$('[prefor=' + name + ']').html(val);
      	}
      });
      
      // TODO: 计算时间-由后台给
      $.ajax({
      	method: 'get',
      	url: 'data/data_getHours.json',
      	success: function(r) {
      		// 模拟异步延时
      		setTimeout(function() {
      			$('[prefor=hours]').html(r.hours);
      		}, 1000);
      	}
      });
      
      $("#preview").popup();
    }
  
    // 提交的方法
    function submit() {
      var data = $('#leaveForm').serializeJSON();
      console.log(data);
      
      var loading = weui.loading('提交中...');
      
      // TODO: 发送数据
      $.ajax({
        method: 'get',
        url: ['data/data_applyLeave_success.json', 'data/data_applyLeave_failed.json'][Math.round(Math.random())],
        success: function(data) {
          if (data.status === 'OK') {
            weui.toast('申请成功', 3000);
            $.closePopup();
            
            setTimeout(function() {
              location.href = 'homepage.html';
            }, 3000);
          }
          else {
            weui.topTips('申请失败: ' + data.msg, {
              duration: 10000
            });
          }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          weui.topTips('提交失败: ' + errorThrown, {
            duration: 10000
          });
        },
        complete: function() {
          loading.hide();
        }
      });
      
      
    }
  </script>
</body>
</html>


